/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package genomemap.data;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import commons.util.ExceptionUtil;

import java.util.*;

/**
 * Contains gene-clone assignment data and methods to modify a genetic (physical) map constrained by
 * a physical (genetic) map using the assignment data.
 *
 * @author Susanta Tewari
 * @version 1.0
 * @history Created on Mar 18, 2012.
 * @since 1.0
 */
public class AssignmentData {

    /*
     * gene map. Genes are keys and assigned clones are values.
     */

    /** Field description */
    private final Map<String, List<String>> g_map;

    /*
     * clone map. Clones are keys and assigned genes are values.
     */

    /** Field description */
    private final Map<String, List<String>> c_map;

    /**
     * @param gene_clone_assignments gene map. Genes are keys and assigned clones are values.
     */
    public AssignmentData(final Map<String, List<String>> gene_clone_assignments) {

        g_map = ImmutableMap.copyOf(gene_clone_assignments);


        // initialize and fill clone-keyed map
        final Map<String, Set<String>> clone_map = new HashMap<>(gene_clone_assignments.size() * 3);

        for (final String gene : g_map.keySet()) {

            for (final String clone : g_map.get(gene)) {

                if (clone_map.get(clone) == null) {
                    clone_map.put(clone, new HashSet<String>(3));
                }

                clone_map.get(clone).add(gene);
            }
        }


        // make immutable set for values
        final Map<String, List<String>> clone_immutable_map = new HashMap<>(clone_map.size());

        for (final String key : clone_map.keySet()) {
            clone_immutable_map.put(key, ImmutableList.copyOf(clone_map.get(key)));
        }

        c_map = ImmutableMap.copyOf(clone_immutable_map);
    }

    /**
     * @return gene assignments
     */
    public Map<String, List<String>> getGeneAssignments() {
        return g_map;
    }

    /**
     * @param gene gene whose clone assignments are requested
     * @return an immutable list of assiged clones
     */
    public List<String> getCloneAssignments(final String gene) {

        if (!g_map.containsKey(gene)) {
            ExceptionUtil.throwIllegalArgEx(getClass(), "AssignmentData_Gene_Not_Found");
        }

        return ImmutableList.copyOf(g_map.get(gene));
    }

    /**
     * @return clone assignments
     */
    public Map<String, List<String>> getCloneAssignments() {
        return g_map;
    }

    /**
     * @param clone clone whose gene assignments arerequested
     * @return an immutable list of gene assignments
     */
    public List<String> getGeneAssignments(final String clone) {

        if (!c_map.containsKey(clone)) {
            ExceptionUtil.throwIllegalArgEx(getClass(), "AssignmentData_Clone_Not_Found");
        }

        return ImmutableList.copyOf(c_map.get(clone));
    }

    /**
     * Provides a modified genetic map using a physical map. .
     *
     * @param physicalMap the physical map that modifies the genetic map
     * @param geneticMap the genetic map that is to be modified
     * @return an unmodifiable map of genes
     */
    public List<String> getModifiedGeneMap(final List<String> geneticMap,
            final List<String> physicalMap) {
        return getModifiedMap(geneticMap, physicalMap, c_map);
    }

    /**
     * Provides a modified physical map using a genetic map.
     *
     * @param geneticMap the genetic map that modifies the physical map
     * @param physicalMap the physical map that is to be modified
     * @return an unmodifiable map of probes
     */
    public List<String> getModifiedProbeMap(final List<String> physicalMap,
            final List<String> geneticMap) {
        return getModifiedMap(physicalMap, geneticMap, g_map);
    }

    /**
     * Map modification algorithm: map --> (criterion) sorted subset --> (embed into the superset)
     * modified map This is explained via an example. Using the assignments, physical map provides
     * an ordering among a subset of genes in the genetic map. That order is then embedded into the
     * genetic map. <p> Say, the physical map is p_map = {P1, P2, P3} and the genetic map is g_map =
     * {G7, G1, G2, G3, G4, G5}. Let us assume the following assignments among genes and probes.P1
     * -> {G1, G3, G6}; P2 -> {G1}; P3 -> {G2} Then the modified genetic map would be {G7, G1, G3,
     * G2, G4, G5}.
     *
     * @param byMap the map used in modification of the <code>fromMap</code>
     * @param fromMap the map to be modified
     * @param assignment_map c_map if byMap is physical and g_map if byMap is genetic
     * @return a new instance of the map created
     */
    @SuppressWarnings("TypeMayBeWeakened")
    static List<String> getModifiedMap(final List<String> fromMap, final List<String> byMap,
                                       final Map<String, ? extends List<String>> assignment_map) {


        // find the ordered elements
        final List<String> ordered_elements = new ArrayList<>();

        for (final String by_map_element : byMap) {

            final List<String> assignees = assignment_map.get(by_map_element);

            if ((assignees != null) && (assignees.size() > 0)) {

                for (final String assignee : assignees) {

                    if (!ordered_elements.contains(assignee) && fromMap.contains(assignee)) {
                        ordered_elements.add(assignee);
                    }
                }
            }
        }


        // embed the ordered elements
        final List<String> modified_map = new ArrayList<>();
        final Iterator<String> itr      = ordered_elements.iterator();

        for (final String aFromMap : fromMap) {

            if (ordered_elements.contains(aFromMap)) {
                modified_map.add(itr.next());
            } else {
                modified_map.add(aFromMap);
            }
        }

        return Collections.unmodifiableList(modified_map);
    }
}
